<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>智能问答系统</title>
  <style>
    /* 全局样式 */
    body {
      font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
      margin: 0;
      padding: 0;
      background: #f7f7f7;
      display: flex;
      height: 100vh;
      overflow: hidden; /* Prevent scroll on body */
    }

    /* 左侧导航栏 */
    .sidebar {
      width: 300px; /* Increased width */
      background: #202123;
      color: #fff;
      padding: 20px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      overflow-y: auto; /* Allow sidebar to scroll if content exceeds height */
    }

    .sidebar h2 {
      font-size: 18px;
      margin-bottom: 20px;
      color: #f1f1f1;
    }

    .sidebar label {
      background: #343541;
      color: #fff;
      border: none;
      padding: 10px;
      border-radius: 5px;
      margin-bottom: 10px;
      cursor: pointer;
      text-align: left;
      transition: background 0.3s ease;
      display: block; /* Make label take full width */
    }

    .sidebar label:hover {
      background: #444654;
    }

    .sidebar input[type="file"] {
      display: none; /* 隐藏默认文件选择框 */
    }

    .sidebar .status {
      font-size: 14px;
      color: #aaa;
      margin-top: 5px;
      margin-bottom: 10px;
      word-break: break-all; /* Prevent overflow */
    }

    /* 新增的工作区管理区域 */
    .workspace-area {
        margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #444;
    }

     .workspace-area label {
        display: block;
        margin-bottom: 5px;
        font-size: 14px;
        color: #f1f1f1;
        background: none; /* Override label style */
        padding: 0;
        cursor: default;
     }

     .workspace-select-container {
        display: flex;
        gap: 10px;
        align-items: center;
        margin-bottom: 10px;
     }

     .workspace-select-container select {
        flex-grow: 1;
        padding: 8px;
        border: 1px solid #555;
        border-radius: 5px;
        background: #343541;
        color: #fff;
        font-size: 14px;
        box-sizing: border-box;
        cursor: pointer;
     }

     .create-workspace-container {
        display: flex;
        gap: 10px;
        align-items: center;
     }

     .create-workspace-container input[type="text"] {
        flex-grow: 1;
        padding: 8px;
        border: 1px solid #555;
        border-radius: 5px;
        background: #343541;
        color: #fff;
        font-size: 14px;
     }

     .create-workspace-container button {
        padding: 8px 15px;
        background: #007BFF;
        color: #fff;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 14px;
        transition: background 0.3s ease;
     }
      .create-workspace-container button:hover {
        background: #0056b3;
     }
     .create-workspace-container button:disabled {
        background-color: #cccccc;
        cursor: not-allowed;
     }


    /* 提示词输入区域 - 移除 */
    /*
    .prompt-area {
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid #444;
    }

    .prompt-area label {
      display: block;
      margin-bottom: 5px;
      font-size: 14px;
      color: #f1f1f1;
      background: none;
      padding: 0;
      cursor: default;
    }

    .prompt-area textarea {
      width: 100%;
      height: 80px;
      padding: 10px;
      border: 1px solid #555;
      border-radius: 5px;
      background: #343541;
      color: #fff;
      font-size: 14px;
      box-sizing: border-box;
      resize: vertical;
    }
    */


    /* 新增的节点和关系输入区域 */
    .allowed-types-area {
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid #444; /* Separator */
    }

    .allowed-types-area label {
      display: block;
      margin-bottom: 5px;
      font-size: 14px;
      color: #f1f1f1;
      background: none; /* Override label style */
      padding: 0;
      cursor: default;
    }

    .allowed-types-area input[type="text"] {
      width: 100%;
      padding: 8px;
      border: 1px solid #555;
      border-radius: 5px;
      background: #343541;
      color: #fff;
      font-size: 14px;
      box-sizing: border-box;
      margin-bottom: 10px; /* Space between node and relation inputs */
    }

    .allowed-types-area input[type="text"]:disabled {
        background-color: #555;
        cursor: not-allowed;
    }


    /* 新增的图谱选择区域 */
     .graph-select-area {
        margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #444; /* Separator */
     }

     .graph-select-area label {
        display: block;
        margin-bottom: 5px;
        font-size: 14px;
        color: #f1f1f1;
        background: none; /* Override label style */
        padding: 0;
        cursor: default;
     }

     .graph-select-area select {
        width: 100%;
        padding: 8px;
        border: 1px solid #555;
        border-radius: 5px;
        background: #343541;
        color: #fff;
        font-size: 14px;
        box-sizing: border-box;
        cursor: pointer;
     }

     .graph-select-area select:disabled {
         cursor: not-allowed;
         background-color: #555;
     }

     /* File upload elements below graph selection */
     .file-upload-area {
        /* Add spacing or borders if needed */
     }


    /* 右侧主内容区 */
    .main-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      background: #fff;
      overflow: hidden; /* Prevent main content from causing scroll */
    }

    /* 顶部标题 */
    .header {
      padding: 15px 20px; /* Adjusted padding */
      border-bottom: 1px solid #ddd;
      background: #f7f7f7;
      flex-shrink: 0; /* Prevent header from shrinking */
    }

    .header h1 {
      font-size: 22px; /* Adjusted font size */
      margin: 0;
    }

    /* 聊天区域 */
    .chat-container {
      flex: 1;
      padding: 20px;
      overflow-y: auto; /* Allow chat area to scroll */
      display: flex;
      flex-direction: column;
      gap: 10px; /* Add space between messages */
    }

    .chat-message {
      max-width: 70%;
      padding: 10px;
      border-radius: 10px;
      line-height: 1.5; /* Improve readability */
      word-break: break-word; /* Break long words */
    }

    .chat-message strong {
        font-weight: bold;
        margin-right: 5px;
    }

    .chat-message.user {
      background: #007BFF;
      color: #fff;
      align-self: flex-end;
    }

    .chat-message.system {
      background: #e9e9eb; /* Lighter grey */
      color: #333;
      align-self: flex-start;
    }

     /* Loading indicator */
    .loading {
        font-style: italic;
        color: #888;
    }


    /* 聊天输入框 */
    .chat-input-container {
      padding: 20px;
      border-top: 1px solid #ddd;
      background: #f7f7f7;
      flex-shrink: 0; /* Prevent input area from shrinking */
    }

    .chat-input {
      display: flex;
      gap: 10px;
      align-items: center; /* Vertical alignment */
    }

    .chat-input input[type="text"] {
      flex: 1;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 16px;
      box-sizing: border-box;
    }

    .chat-input button {
      padding: 10px 20px;
      background: #007BFF;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
      transition: background 0.3s ease;
      flex-shrink: 0; /* Prevent button from shrinking */
    }

    .chat-input button:hover {
      background: #0056b3;
    }

    .chat-input button:disabled {
        background-color: #cccccc;
        cursor: not-allowed;
    }

  </style>
</head>
<body>
  <!-- 左侧导航栏 -->
  <div class="sidebar">
    <h2>功能导航</h2>

    <!-- 工作区管理区域 -->
    <div class="workspace-area">
        <label for="workspaceSelect">选择或创建工作区:</label>
        <div class="workspace-select-container">
            <select id="workspaceSelect">
                <option value="">-- 请选择工作区 --</option>
                <!-- Workspaces will be populated here by JavaScript -->
            </select>
             <div id="workspaceStatus" class="status">正在加载工作区列表...</div>
        </div>
        <div class="create-workspace-container">
            <input type="text" id="newWorkspaceName" placeholder="输入新工作区名称">
            <button id="createWorkspaceBtn">创建</button>
        </div>

    </div>



    <!-- 允许的节点和关系输入区域 -->
    <div class="allowed-types-area">
        <label for="allowedNodesInput">允许的节点类型 (逗号分隔):</label>
        <input type="text" id="allowedNodesInput" placeholder="例如: DrugType, SpecificDrug, Function, ApplicableSymptom, Usage, Precaution" value="DrugType, SpecificDrug, Function, ApplicableSymptom, Usage, Precaution" disabled>
        <label for="allowedRelationsInput">允许的关系类型 (逗号分隔):</label>
        <input type="text" id="allowedRelationsInput" placeholder="例如:IS_A_TYPE_OF, HAS_MAIN_FUNCTION, APPLIES_TO, HAS_USAGE, HAS_PRECAUTION, INCLUDES_EXAMPLE" value="IS_A_TYPE_OF, HAS_MAIN_FUNCTION, APPLIES_TO, HAS_USAGE, HAS_PRECAUTION, INCLUDES_EXAMPLE" disabled>
    </div>


     <!-- File upload elements -->
    <div class="file-upload-area">
        <label for="pdfInput" id="pdfUploadLabel">上传 PDF 文件</label>
        <input type="file" id="pdfInput" accept=".pdf" disabled> <!-- Disabled initially -->
        <div id="pdfStatus" class="status">请先选择工作区。</div>

        <!-- Triple upload is likely not functional with current backend, keeping for structure -->
        <label for="tripleInput" id="tripleUploadLabel">上传三元组文件 (.pkl, .ttl)</label>
        <input type="file" id="tripleInput" accept=".pkl,.ttl" disabled> <!-- Disabled initially -->
        <div id="tripleStatus" class="status">请先选择工作区。</div>
    </div>


    <!-- 图谱选择区域 -->
    <div class="graph-select-area">
        <label for="graphSelect">选择图谱进行问答:</label>
        <select id="graphSelect" disabled> <!-- Disabled initially -->
            <option value="">-- 请选择图谱 --</option>
            <!-- Graphs will be populated here by JavaScript -->
        </select>
        <div id="graphListStatus" class="status">请先选择工作区。</div>
    </div>

  </div>

  <!-- 右侧主内容区 -->
  <div class="main-content">
    <!-- 顶部标题 -->
    <div class="header">
      <h1>智能图谱分析与问答系统</h1>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-container" id="chatContainer">
      <div class="chat-message system"><strong>系统:</strong> 你好！请先在左侧选择一个工作区，或创建一个新的工作区。</div>
    </div>

    <!-- 聊天输入框 -->
    <div class="chat-input-container">
      <div class="chat-input">
        <input type="text" id="chatInput" placeholder="请先选择图谱进行问答..." disabled> <!-- Disabled initially -->
        <button id="chatSendBtn" disabled>发送</button> <!-- Disabled initially -->
      </div>
    </div>
  </div>

  <script>
    // Get references to new workspace elements
    const workspaceSelect = document.getElementById('workspaceSelect');
    const newWorkspaceNameInput = document.getElementById('newWorkspaceName');
    const createWorkspaceBtn = document.getElementById('createWorkspaceBtn');
    const workspaceStatus = document.getElementById('workspaceStatus');

    // Get references to new allowed types elements
    const allowedNodesInput = document.getElementById('allowedNodesInput');
    const allowedRelationsInput = document.getElementById('allowedRelationsInput');

    // Get references to existing elements
    const pdfInput = document.getElementById('pdfInput');
    const pdfUploadLabel = document.getElementById('pdfUploadLabel'); // Get label to manage cursor/styling
    const pdfStatus = document.getElementById('pdfStatus');
    const tripleInput = document.getElementById('tripleInput'); // Still here but backend endpoint not implemented
    const tripleUploadLabel = document.getElementById('tripleUploadLabel'); // Get label
    const tripleStatus = document.getElementById('tripleStatus'); // Still here but backend endpoint not implemented

    const graphSelect = document.getElementById('graphSelect'); // Get the new select element
    const graphListStatus = document.getElementById('graphListStatus'); // Status for graph list
    const chatLog = document.getElementById('chatContainer');
    const chatInput = document.getElementById('chatInput');
    const chatSendBtn = document.getElementById('chatSendBtn');

    let currentWorkspaceId = null; // 当前选中的工作区ID
    let currentGraphId = null; // 当前选中的图谱ID

    // Function to append message to chat log
    function appendChatMessage(text, sender, isLoading = false) {
      const msgDiv = document.createElement('div');
      msgDiv.className = `chat-message ${sender} ${isLoading ? 'loading' : ''}`;
      // Basic sanitization for displayed text to prevent simple HTML injection
      const safeText = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
      msgDiv.innerHTML = `<strong>${sender === 'user' ? '你' : '系统'}:</strong> ${safeText}`;
      chatLog.appendChild(msgDiv);
      chatLog.scrollTop = chatLog.scrollHeight;
      return msgDiv; // Return the element in case we need to update it (for loading)
    }

    // Function to enable or disable UI elements based on state
    function updateUIState() {
        const workspaceSelected = currentWorkspaceId !== null && currentWorkspaceId !== "";
        const graphSelected = currentGraphId !== null && currentGraphId !== "";

        // Workspace Creation
        createWorkspaceBtn.disabled = false; // Always enabled
        newWorkspaceNameInput.disabled = false; // Always enabled

        // Allowed Types Inputs
        allowedNodesInput.disabled = !workspaceSelected;
        allowedRelationsInput.disabled = !workspaceSelected;


        // File Uploads
        pdfInput.disabled = !workspaceSelected;
        pdfUploadLabel.style.cursor = workspaceSelected ? 'pointer' : 'not-allowed';
        tripleInput.disabled = !workspaceSelected;
        tripleUploadLabel.style.cursor = workspaceSelected ? 'pointer' : 'not-allowed';
        pdfStatus.innerText = workspaceSelected ? '等待上传 PDF...' : '请先选择工作区。';
        tripleStatus.innerText = workspaceSelected ? '等待上传三元组文件...' : '请先选择工作区。';


        // Graph Selection
        graphSelect.disabled = !workspaceSelected;
        graphListStatus.innerText = workspaceSelected ? '正在加载图谱列表...' : '请先选择工作区。';


        // Chat
        chatInput.disabled = !graphSelected;
        chatSendBtn.disabled = !graphSelected;
        chatInput.placeholder = graphSelected ? "请输入关于图谱的查询问题..." : (workspaceSelected ? "请选择图谱进行问答..." : "请先选择工作区...");
    }


    // Function to fetch and populate the workspace list
    async function fetchWorkspaces() {
        workspaceStatus.innerText = "正在加载工作区列表...";
        updateUIState(); // Disable relevant UI

        try {
            const response = await fetch('http://localhost:8001/list_workspaces');
            const workspaces = await response.json();

            // Clear existing options except the default
            workspaceSelect.innerHTML = '<option value="">-- 请选择工作区 --</option>';

            if (response.ok && Array.isArray(workspaces)) { // Check if response is an array
                workspaces.forEach(ws => {
                    const option = document.createElement('option');
                    option.value = ws.workspace_id;
                    option.innerText = ws.name || ws.workspace_id; // Use name if available
                    workspaceSelect.appendChild(option);
                });
                workspaceStatus.innerText = `加载成功，找到 ${workspaces.length} 个工作区。`;
            } else {
                 workspaceStatus.innerText = "加载工作区列表失败：" + (workspaces.detail || "未知错误");
            }
        } catch (error) {
            console.error("Error fetching workspaces:", error);
            workspaceStatus.innerText = "加载工作区列表时发生错误。";
        } finally {
             updateUIState(); // Update state after loading attempt
        }
    }

    // Function to fetch and populate the graph list for a given workspace
    async function fetchGraphs(workspaceId) {
        if (!workspaceId) {
            graphSelect.innerHTML = '<option value="">-- 请选择图谱 --</option>';
            graphListStatus.innerText = '请先选择工作区。';
            currentGraphId = null;
            updateUIState();
            return;
        }

        graphListStatus.innerText = `正在加载工作区 (${workspaceSelect.options[workspaceSelect.selectedIndex].text}) 中的图谱...`;
        currentGraphId = null; // Clear selected graph when workspace changes
        graphSelect.value = ""; // Reset graph dropdown

        updateUIState(); // Disable chat and graph select temporarily

        try {
            const response = await fetch(`http://localhost:8001/list_graphs?workspace_id=${workspaceId}`);
            const graphs = await response.json();

            // Clear existing options except the default
            graphSelect.innerHTML = '<option value="">-- 请选择图谱 --</option>';

            if (response.ok && Array.isArray(graphs)) { // Check if response is an array
                graphs.forEach(graph => {
                    const option = document.createElement('option');
                    option.value = graph.graph_id;
                    option.innerText = graph.name || graph.graph_id; // Use name if available
                    graphSelect.appendChild(option);
                });
                graphListStatus.innerText = `加载成功，找到 ${graphs.length} 个图谱。`;
            } else {
                graphListStatus.innerText = "加载图谱列表失败：" + (graphs.detail || "未知错误");
            }
        } catch (error) {
            console.error("Error fetching graphs:", error);
            graphListStatus.innerText = "加载图谱列表时发生错误。";
        } finally {
            updateUIState(); // Update state after loading attempt (enables graph select)
        }
    }

     // Event listener for workspace selection change
    workspaceSelect.addEventListener('change', async (event) => {
        currentWorkspaceId = event.target.value;
        currentGraphId = null; // Reset graph selection when workspace changes
        graphSelect.value = ""; // Reset graph dropdown

        if (currentWorkspaceId) {
             appendChatMessage(`已选择工作区：${workspaceSelect.options[workspaceSelect.selectedIndex].text}`, 'system');
             await fetchGraphs(currentWorkspaceId); // Fetch graphs for the selected workspace
        } else {
             appendChatMessage("请选择一个工作区。", 'system');
             fetchGraphs(null); // Clear graph list if no workspace selected
        }
         updateUIState(); // Update state based on new selection
    });

    // Event listener for create workspace button
    createWorkspaceBtn.addEventListener('click', async () => {
        const workspaceName = newWorkspaceNameInput.value.trim();
        if (!workspaceName) {
            alert("工作区名称不能为空。");
            return;
        }

        workspaceStatus.innerText = `正在创建工作区 "${workspaceName}"...`;
        createWorkspaceBtn.disabled = true;
        newWorkspaceNameInput.disabled = true;
        updateUIState(); // Disable other parts

        try {
            const formData = new FormData();
            formData.append('name', workspaceName);

            const response = await fetch('http://localhost:8001/create_workspace', {
                method: 'POST',
                body: formData
            });
            const data = await response.json();

            if (response.ok) {
                workspaceStatus.innerText = `工作区创建成功！ID：${data.workspace_id}`;
                newWorkspaceNameInput.value = ''; // Clear input
                // Refresh the workspace list and select the new one
                await fetchWorkspaces();
                workspaceSelect.value = data.workspace_id;
                currentWorkspaceId = data.workspace_id;
                // Also fetch graphs for the new workspace
                await fetchGraphs(currentWorkspaceId);
                appendChatMessage(`已创建并选择工作区：${data.name}`, 'system');

            } else {
                workspaceStatus.innerText = "创建工作区失败：" + (data.detail || "未知错误");
                 appendChatMessage(`创建工作区失败：${data.detail || "未知错误"}`, 'system');
            }
        } catch (error) {
            console.error("Error creating workspace:", error);
            workspaceStatus.innerText = "创建工作区时发生错误。";
             appendChatMessage(`创建工作区时发生错误：${error}`, 'system');
        } finally {
            createWorkspaceBtn.disabled = false;
            newWorkspaceNameInput.disabled = false;
            updateUIState(); // Update state after operation
        }
    });


    // PDF 文件上传处理
    pdfInput.addEventListener('change', async () => {
      if (!pdfInput.files.length) return;
      const file = pdfInput.files[0];

      if (!currentWorkspaceId) {
           pdfStatus.innerText = "错误：未选择工作区。";
           appendChatMessage("错误：未选择工作区，无法上传 PDF。", 'system');
           pdfInput.value = ''; // Clear file input
           return;
      }


      const allowedNodes = allowedNodesInput.value.trim(); // Get allowed nodes
      const allowedRelations = allowedRelationsInput.value.trim(); // Get allowed relations


      const formData = new FormData();
      formData.append('pdf', file);
      formData.append('workspace_id', currentWorkspaceId); // Include current workspace ID

      if (allowedNodes) { // Only append allowed nodes if not empty
          formData.append('allowed_nodes_str', allowedNodes);
      }
       if (allowedRelations) { // Only append allowed relations if not empty
          formData.append('allowed_relations_str', allowedRelations);
      }


      pdfStatus.innerText = `正在上传 "${file.name}" 并处理图谱...`;
      const loadingMsgElement = appendChatMessage(`正在上传 "${file.name}" 并处理图谱...`, 'system', true);
      updateUIState(); // Disable relevant UI during upload

      try {
        const response = await fetch('http://localhost:8001/upload', {
          method: 'POST',
          body: formData
        });
        const data = await response.json();

        // Remove the loading message
        if (loadingMsgElement) {
            loadingMsgElement.remove();
        }

        if (response.ok) {
          pdfStatus.innerText = `处理成功！图谱ID：${data.graph_id}`;
          // Refresh the graph list for the current workspace and select the new one
          await fetchGraphs(currentWorkspaceId);
          if (data.graph_id) {
              graphSelect.value = data.graph_id;
              currentGraphId = data.graph_id; // Save the new graph ID
               appendChatMessage(`图谱创建成功！图谱ID是：${data.graph_id} (名称: ${data.graph_name || '无名称'})。总共提取了 ${data.triple_count} 个三元组。`, 'system');
                if (data.query_answer) {
                    appendChatMessage(`以下是使用默认问题 ("药品种类?") 的示例查询结果：${data.query_answer}`, 'system');
                } else {
                     appendChatMessage(`未能获取示例查询结果。`, 'system');
                }
          } else {
              // Case where triples were 0 and no graph was created
               appendChatMessage(`图谱处理完成，但没有提取到有效的三元组，未能创建图谱。`, 'system');
               currentGraphId = null;
          }


        } else {
          pdfStatus.innerText = "处理失败：" + (data.detail || "未知错误");
           appendChatMessage(`图谱处理失败：${data.detail || "未知错误"}`, 'system');
           currentGraphId = null; // Clear graph ID on failure
        }
      } catch (error) {
        console.error(error);
        pdfStatus.innerText = "上传或处理过程中发生错误。";
         // Remove the loading message
        if (loadingMsgElement) {
            loadingMsgElement.remove();
        }
        appendChatMessage(`上传或处理过程中发生错误：${error}`, 'system');
        currentGraphId = null; // Clear graph ID on error
      } finally {
          pdfInput.value = ''; // Clear the file input
          updateUIState(); // Update state after operation
      }
    });

    // 三元组上传处理 (This endpoint /create_graph is NOT implemented in main.py)
    // Keeping the code structure but noting it's non-functional with the provided backend
    tripleInput.addEventListener('change', async () => {
      if (!tripleInput.files.length) return;
      const file = tripleInput.files[0];

       if (!currentWorkspaceId) {
           tripleStatus.innerText = "错误：未选择工作区。";
           appendChatMessage("错误：未选择工作区，无法上传三元组。", 'system');
           tripleInput.value = ''; // Clear file input
           return;
      }

      const formData = new FormData();
      formData.append('file', file); // Assuming backend expects 'file'
      // formData.append('workspace_id', currentWorkspaceId); // You'd likely need to send workspace_id here too

      tripleStatus.innerText = `正在上传 "${file.name}" 并创建图谱...`;
       const loadingMsgElement = appendChatMessage(`正在上传 "${file.name}" 并尝试创建图谱... (注意: 此功能在当前后端可能未实现)`, 'system', true);
       updateUIState();

      try {
        // WARNING: This endpoint /create_graph is NOT implemented in the provided main.py
        // You would need to add this endpoint to main.py if you want to support it.
        // It would likely need to read the file content (pkl or ttl), parse it into triples,
        // and then call graph_processor.create_whyhow_graph(..., workspace_id=currentWorkspaceId).
        const response = await fetch('http://localhost:8001/create_graph', {
        // const response = await fetch('/create_graph', { // Use relative path if hosted together
          method: 'POST',
          body: formData
        });
        const data = await response.json(); // This line might fail if the endpoint doesn't exist

        // Remove the loading message
        if (loadingMsgElement) {
            loadingMsgElement.remove();
        }

        if (response.ok) {
          tripleStatus.innerText = "图谱创建成功！图谱ID：" + data.graph_id;
          currentGraphId = data.graph_id; // Save the new graph ID
           // Automatically select the newly created graph in the dropdown
           await fetchGraphs(currentWorkspaceId); // Refresh list and then select
           if (data.graph_id) {
               graphSelect.value = currentGraphId;
               appendChatMessage(`图谱创建成功！图谱ID是：${data.graph_id}`, 'system');
           }


        } else {
          tripleStatus.innerText = "处理失败：" + (data.detail || "未知错误");
          appendChatMessage(`图谱创建失败：${data.detail || "未知错误"}`, 'system');
           currentGraphId = null;
        }
      } catch (error) {
        console.error(error);
        tripleStatus.innerText = "上传过程中发生错误。";
        // Remove the loading message
        if (loadingMsgElement) {
            loadingMsgElement.remove();
        }
        appendChatMessage(`上传过程中发生错误：${error} (后端 /create_graph 接口可能未实现)`, 'system');
        currentGraphId = null;
      } finally {
         tripleInput.value = ''; // Clear the file input
         updateUIState();
      }
    });

    // Event listener for graph selection change
    graphSelect.addEventListener('change', (event) => {
        currentGraphId = event.target.value;
        if (currentGraphId) {
            appendChatMessage(`已选择图谱：${graphSelect.options[graphSelect.selectedIndex].text}`, 'system');
        } else {
            appendChatMessage("请选择一个图谱进行问答。", 'system');
        }
        updateUIState(); // Update state based on new selection (enables chat if graph selected)
    });

    // 聊天交互处理
    chatSendBtn.addEventListener('click', async () => {
      const message = chatInput.value.trim();
      if (!message) return;
      if (!currentGraphId) {
        appendChatMessage("请先选择一个图谱进行问答。", 'system');
        return;
      }

      // Display user message
      appendChatMessage(message, 'user');
      chatInput.value = ''; // Clear input
      updateUIState(); // Disable input/button while waiting

      const loadingMsgElement = appendChatMessage("正在思考...", 'system', true); // Add loading message

      try {
        const response = await fetch('http://localhost:8001/chat', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            message: message,
            graph_id: currentGraphId // Send the selected graph ID
          })
        });
        const data = await response.json();

         // Remove the loading message
        if (loadingMsgElement) {
            loadingMsgElement.remove();
        }

        if (response.ok) {
          appendChatMessage(data.reply, 'system');
        } else {
           appendChatMessage(`错误 (${response.status}): ${data.detail || "未知错误"}`, 'system');
        }
      } catch (error) {
        console.error("Error during chat:", error);
        // Remove the loading message
        if (loadingMsgElement) {
            loadingMsgElement.remove();
        }
        appendChatMessage(`发送消息时发生错误：${error}`, 'system');
      } finally {
         updateUIState(); // Re-enable input/button based on currentGraphId
      }
    });

    // 支持回车键发送消息
    chatInput.addEventListener('keyup', (event) => {
      if (event.key === 'Enter' && !chatSendBtn.disabled) {
        event.preventDefault(); // Prevent default form submission if input was in a form
        chatSendBtn.click();
      }
    });

    // Initial setup on page load
    document.addEventListener('DOMContentLoaded', () => {
        // Fetch and populate the workspace list when the page loads
        fetchWorkspaces();

        // Set initial status messages
        workspaceStatus.innerText = '正在加载工作区列表...';
        pdfStatus.innerText = '请先选择工作区。';
        tripleStatus.innerText = '请先选择工作区。';
        graphListStatus.innerText = '请先选择工作区。';

        // Ensure UI is disabled initially
        updateUIState();
    });

  </script>
</body>
</html>
